% elp2xyz
% Christopher J. Whalen
% University of Illinois
% 01/24/05 - Date Created
% 01/24/05 - Date Last Modified

% purpose - to read in the elp file without using the importdata command

function [xyz, opt_label] = elp2xyz(elp_file);   

% input_filename = elp_file;
% text_array = importdata(input_filename, 's');
% if ispc
%     text_array = importdata(input_filename, 's');
% elseif isunix
	fid=fopen(elp_file);
	text_array = cell(1,1); 
	i = 1;
	while 1
        text_line = fgetl(fid);
        if ~ischar(text_line), break, end
        text_array(i,1) = cellstr(text_line);
        i=i+1;
	end
	fclose(fid);
% end
text_array_rows = size(text_array,1);

i = 17;    %digitized points always start on row 17 of elp file
k = 1;     %row counter for xyz matrix and opt_label
m = i - 1; %indexes for the label

% Opt_labels for Fiducials
opt_label = {' NZ';' LPA';' RPA'};


% Read in Fiducials
for j=10:12       %fiducials start on 10 and end on row 12
    xyz(k,:) = (sscanf(strrep(char(text_array(j,1)),'%F',''),'%f' )).'; %above converts string into numeric format. also gets rid of %F in text line. more explained in next while loop  
    k = k + 1;
end

% Read in NonFiducial Digitized Points and Label
while i <= text_array_rows   
    xyz(k,:) = (sscanf(char(text_array(i,1)),'%f')).'; %Converts imported row into numeric value. 4 steps inside to out. 1.obtains text 2. converts to char 3 converts to column num matrix 4. transposes to row vector
    opt_label(k,:) = strrep(text_array(m),'%N','');
    k = k + 1; %counter for xyz matrix
    i = i + 5; %counter to pick out rows which contain digitized points from elp file
    m = i - 1;    
end

% Deblanking to match src and det label
opt_label = char(opt_label);
opt_label(:,1)= [];
opt_label = cellstr(opt_label);
% clear text_array;

if size(xyz,1)==0
    fprintf('\nError: elp file contains no points\n');
elseif size(xyz,1)~=size(opt_label,1)
    fprintf('\nError: number of digitized point coordinates is not equal to the number of optode labels (check elp file for formatting issues)\n');
end

fprintf('\nELP file contains %1.0f digitized points\n', size(xyz,1));


